//评论模块的路由

var express = require("express");
var router = express.Router();
var { checkSession, dateFormat } = require("../utils/index");
const { Mvs, Comment } = require("../utils/model");
const { log } = require("debug");

router.get("/test", (req, res) => {
    res.send("test-test-comment")
})//测试成功

router.get("/index", (req, res) => {
    checkSession(req, res, () => {
        var { mid } = req.query;
        var obj = {}
        if (mid) {
            obj = { id: mid }
        }
        const findOneData = function (obj, callback) {
            Mvs.findOne(obj)
                .then(result => {
                    callback(result);
                })
        }
        findOneData(obj, (result) => {
            res.render("comment.ejs", {
                username: req.session.username,
                result
            })
        })
    })
})

//提交电影评论
router.post("/submit", (req, res) => {
    const query = req.query;
    const body = req.body;
    checkSession(req, res, () => {
        Mvs.findOne({
            id: query.mid,
        }).then(movie => {
            body.time = new Date(),
            body.author = req.session.username;
            body.mid = query.mid;
            body.movie = movie;
            Comment.insertMany(body)
                .then(result => {
                    res.redirect("/comment/mlist"); //重定向！！！
                })
        })
    })
})

//评论列表
router.get("/mlist", (req, res) => {
    checkSession(req, res, () => {
        var {
            pageSize,
            page
        } = req.query;
        var total = 0; //总条数
        var totalPage = 0;//总页数
        pageSize = pageSize * 1 || 5; //每页的数量
        page = page * 1 || 1;//页码 默认显示第一页
        Comment.find({}, {})
            .then(data => {
                total = data.length;//读取数据库内容得到评论总条数
                totalPage = Math.ceil(total / pageSize);//评论总页码
                page = page < 1 ? 1 : page;
                page = page > totalPage ? totalPage : page;//此处判断用户输入页码数是否可行,不能小于1，不能大于总页码
                Comment.find({}, {})
                    .skip((page - 1) * pageSize)
                    .limit(pageSize)
                    .sort({ _id: -1 })
                    .then(result => {
                        result = result.map(item => {
                            item = { ...item._doc, time: dateFormat(item.time) }
                            return item;
                        })
                        res.render("mlist", {
                            username: req.session.username,
                            result,
                            total,
                            page,
                            pageSize,
                            totalPage
                        })
                    })
            })
    })
})



//当前电影的所有评论
router.get("/moviepin", (req, res) => {
    checkSession(req, res, () => {
        var { mid } = req.query;
        Comment.find({
            mid
        }, {})
            .sort({ _id: -1 })
            .then(result => {
                result = result.map(item => {
                    item = { ...item._doc, time: dateFormat(item.time) }
                    return item;
                })
                res.render("moviepin", {
                    result,
                    movie: result[0].movie,
                    username: req.session.username
                })
            })
    })
})

//xx的电影评论
router.get("/my", (req, res) => {
    var { author } = req.query;
    Comment.find({ author }, {})
        .then(result => {
            result = result.map(item => {
                item = { ...item._doc, time: dateFormat(item.time) };
                return item;
            })
            res.render("my", {
                result,
                author,
                username: req.session.username
            })
        })
})

//评论详情
router.get("/detail", (req, res) => {
    var { _id } = req.query;
    Comment.findOne({
        _id
    }, {}).then(result => {
        result = { ...result._doc, time: dateFormat(result.time) };
        res.render('detail', {
            result,
            username: req.session.username
        })
    })
})

//添加评论的回复
router.post("/answersubmit", (req, res) => {
    checkSession(req, res, () => {
        var {
            _id,
            subtitle
        } = req.body;
        Comment.findOne({//先利用_id找到数据库中的评论回复，将新的回复push进去
            _id
        }, {})
            .then(data => {
                var answer = data.answer || [];
                answer.push({
                    subtitle,
                    id: answer.length,
                    author: req.session.username,
                    time: dateFormat(new Date())//对push进去的time做处理，之后取出来直接用
                });
                Comment.updateMany({//再去修改数据库中内容
                    _id
                }, {
                    $set: {
                        answer
                    }
                }).then(result => {
                    res.json({//此处是用ajxs所以需要返回一个json数据
                        code: 200,
                        msg: "回复评论成功",
                        result,
                        type: 1
                    })
                })
            })
    })
})

//删除评论路由
router.post("/delsubmit", (req, res) => {
    checkSession(req, res, () => {
        var { _id } = req.body;
        Comment.remove({
            _id
        }).then(result => {
            res.json({
                code: 200,
                msg: "删除评论成功",
                result,
                type: 1
            })
        })
    })

})

// 电影修改评论页面 
router.get("/update", (req, res) => {
    checkSession(req, res, () => {
        var { _id } = req.query;
        Comment.findOne({
            _id
        }, {}).then(result => {
            res.render('update', {
                result,
                username:req.session.username
            })
        })
    })
})
//提交修改评论
router.post("/xiugai",(req,res)=>{
    var query = req.query;
    var body = req.body;
    Comment.updateMany({
        _id:query._id
    },{
        $set:{
            title:body.title,
            content:body.content
        }
    }).then(result=>{
        res.send(`<script>alert('修改成功');location.href='/comment/mlist'</script>`)
    })
})

module.exports = router;